
var engine = require('../scripts/network/MatchvsEngine');
var response = require('../scripts/network/MatchvsResponse');
var msg = require('../scripts/network/MatchvsMessage');
var mvs = require('../scripts/network/gameData');

cc.Class ({
    extends: cc.Component,

    properties: {
        loginButton: cc.Button,
    },

    onLoad: function () {
        cc.director.preloadScene('fight');   //使用预加载解决 调用监听无效问题
        cc.director.preloadScene('main');
        response.prototype.bind();
        response.prototype.init(this);
        this.node.on(msg.MATCHVS_INITRESPONSE,this.initResponse,this);                //监听 InitResponse 回调
        this.node.on(msg.MATCHVS_REGISTERUSERRESPONSE,this.registerUserResponse,this);//监听 RegisterUserResponse 回调
        this.node.on(msg.MATHCVS_LOGINRESPONSE,this.loginResponse,this);              //监听 LoginRespnse 回调
        this.loginButton.node.on('click',this.init,this);       //按钮点击监听
    },

    init: function () {
        var result = engine.prototype.init();
        if(result == 0){
            console.log("调用init()成功");
        }else {
            console.log("调用init()失败");
        }
    },

    initResponse: function (status) {
        if(status == 200) {
            console.log("初始化成功");
            var result = engine.prototype.registerUser();
            if (result == 0) {
                console.log("调用registerUser()成功");
            }else if (result == -1) {
                console.log("调用registerUser()失败");
            }else if (result == -2) {
                console.log("未初始化");
            }
        }else {
            console.log("初始化失败");
        }
    },

    registerUserResponse: function (userInfo) {
        if(userInfo.status == 0) {
            console.log("用户注册成功");
            console.log(userInfo);
            mvs.userInfo.userID = userInfo.userID; //将用户信息存储到gameData.userInfo中
            mvs.userInfo.token = userInfo.token;
            mvs.userInfo.userName = userInfo.name;
            var result = engine.prototype.login(userInfo.userID,userInfo.token,userInfo.name);
            if(result == 0){
                console.log("调用login()成功");
            }else if (result == -1) {
                console.log("调用login()失败");
            }else if (result == -2) {
                console.log("未初始化");
            }
        }else {
            console.log("用户注册失败");
        }
    },

    loginResponse: function (MsLoginRsp) {
        if(MsLoginRsp.status == 200) {
            console.log("登入成功");
            this.guanbijianting();
            cc.director.loadScene('main');
        }else {
            console.log("登入失败,错误码:" + MsLoginRsp.status);
        }
    },

    /**
     * 关闭监听回调
     */
    guanbijianting: function () {
        this.node.off(msg.MATCHVS_INITRESPONSE,this.initResponse,this);
        this.node.off(msg.MATCHVS_REGISTERUSERRESPONSE,this.registerUserResponse,this);
        this.node.off(msg.MATHCVS_LOGINRESPONSE,this.loginResponse,this);
    }
})